// vuex的state  全局存储

// 引入
import { login, getUserInfo, logout } from '@/api/auth/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'

// 定义全局数据 不能直接 点取值 必须通过mutations进行
const state = {
    token: getToken(), // token
    user: '', // 用户对象
}

// 保持全局数据的干净 不被污染 不可以掉异步请求方法
const mutations = {
    SET_TOKEN_STATE: (state, token) => {
        state.token = token
    },
    SET_USER_STATE: (state, user) => {
        state.user = user
    }
}

// 异步请求
const actions = {
    // 用户登录
    login({ commit }, userInfo) {
        console.log(userInfo)
        const { name, pass, rememberMe } = userInfo
        return new Promise((resolve, reject) => {
            // 登录接口 向服务器发请求的
            login({ username: name.trim(), password: pass, rememberMe: rememberMe }).then(response => {
                const { data } = response
                // 保存到vuex的state中
                commit('SET_TOKEN_STATE', data.token)
                // 向js-cookie也保存一份
                setToken(data.token)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // 获取用户信息
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getUserInfo().then(response => {
                const { data } = response
                console.log(data)
                if (!data) {
                    commit('SET_TOKEN_STATE', '')
                    commit('SET_USER_STATE', '')
                    removeToken()
                    resolve()
                    reject('验证失败,请重新登录')
                }
                commit('SET_USER_STATE', data)
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // 注销
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            logout(state.token).then((response) => {
                console.log(response)
                // 将用户状态全部清空
                commit("SET_TOKEN_STATE", "")
                commit("SET_USER_STATE", "")
                // 从cookie中也清掉
                removeToken()
                resolve()
            }).catch((error) => {
                reject(error)
            })
        })
    },
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}